package com.icss.ah.productPrice.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.bean.EasyuiDataGridJson;
import com.icss.ah.login.bean.UserInfoBean;
import com.icss.ah.postTrade.service.PostTradeService;
import com.icss.ah.productPrice.service.ProductPriceService;
import com.icss.ah.productPublish.service.ProductPublishService;
/**
 * 商品价格
 * @author whr
 * @descr 商品价格  修改 审核
 */
@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class ProductPriceAction extends BaseAction{
	@Autowired
	private PostTradeService postTradeService;
	@Autowired
	private ProductPriceService productPriceService;
	@Autowired
	private ProductPublishService productPublishService;
	private final Logger errlog = Logger.getLogger("E");
	/**
	 * 商品价格修改  UI
	 */
	@SuppressWarnings("unchecked")
	public String modifyPrice(){
		request = getRequest();
		String productId = request.getParameter("productId")==null?"":request.getParameter("productId");
		String status = request.getParameter("status")==null?"0":request.getParameter("status");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("productId", productId);
		map.put("status", status);
		//商品信息
		Map<String, Object> proInfo = productPublishService.getProInfo(map);
		//产品价格
		List<Map<String, Object>> priceList = productPriceService.getProductPrice("ProductPriceBean.getProductList", map);
		if(priceList.size()>0&&priceList!=null){
			request.setAttribute("flag", "true");
			status = priceList.get(0).get("STATUS") + "";			
		}
		String itemName = postTradeService.getCascadeName((String)proInfo.get("categoryCode"));
		request.setAttribute("productId", productId);//商品编码传入页面
		request.setAttribute("pro", proInfo);
		request.setAttribute("itemName", itemName);
		request.setAttribute("status", status);
		return "toModifyPricePage";
	}
	
	/**
	 * 商品价格查询
	 */
	public void queryProductPriceInfo(){
		JSONObject json = new JSONObject();
		request = getRequest();
		String productId = request.getParameter("productId")==null?"":request.getParameter("productId");
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("productId", productId);			
			List<Map<String, Object>> priceList = productPriceService.getProPrice(map);			
			json.put("priceList", priceList);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPriceAction|queryProductPriceInfo：",e);
		} finally {
			str2Resp(json.toString());
		}
	}
	/**
	 * 价格区间  修改后待审核list
	 */
	@SuppressWarnings("unchecked")
	public void queryProductPriceInfo2(){
		JSONObject json = new JSONObject();
		request = getRequest();
		String productId = request.getParameter("productId")==null?"":request.getParameter("productId");
		String status = request.getParameter("status")==null?"0":request.getParameter("status");
		String passed = request.getParameter("passed")==null?"":request.getParameter("passed");
		String uuid = request.getParameter("uuid")==null?"":request.getParameter("uuid");
		
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("productId", productId);
			map.put("status", status);
			map.put("uuid", uuid);
			map.put("passed", passed);
			
			System.out.println("========map:"+map);
			
			List<Map<String, Object>> priceList2 = new ArrayList<Map<String,Object>>();
			if("1".equals(passed)){//通过审核
				priceList2 = productPriceService.getProductPrice("ProductPriceBean.getProductList2", map);
			}else{//待审核
				priceList2 = productPriceService.getProductPrice("ProductPriceBean.getProductList", map);			
			}
			json.put("priceList2", priceList2);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPriceAction|queryProductPriceInfo2：",e);
		} finally {
			str2Resp(json.toString());
		}
	}
	/**
	 * 商品价格修改
	 */
	public void modifyProductPrice(){
		JSONObject json = new JSONObject();
		request = getRequest();
		String userCode=getUserCodeFromSession();
		UserInfoBean userInfo=getUserInfo(userCode);
		String shopId=userInfo.getShopId();
		String corpId = userInfo.getCorpId();
		String productId = request.getParameter("productId")==null?"":request.getParameter("productId");
		String opeFlag = request.getParameter("opeFlag")==null?"":request.getParameter("opeFlag");
		String price = request.getParameter("price")==null||"".equals(request.getParameter("price"))?"0":request.getParameter("price");
		try {
			
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("productId", productId);
			map.put("shopId", shopId);
			map.put("corpId", corpId);
			map.put("createPerson", userCode);
			map.put("retailPrice", price);
			map.put("uuid", UUID.randomUUID().toString());
			map.put("purchasePrice", price);				
			map.put("purchaseLow", "1");
			map.put("purchaseType", 1);
			map.put("purchaseUp","-1");
			map.put("sortNum", 1);
			if("save".equals(opeFlag)){
				map.put("status", "0");
			} else if("submit".equals(opeFlag)){
				map.put("status", "1");
			}
			
			boolean result = productPriceService.modifyProductPriceSave(map);
			if(result){
				json.put("result", "1");
			} else {
				json.put("result", "2");
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPriceAction|save：",e);
			json.put("result", "2");
		} finally {
			str2Resp(json.toString());
		}
	}
	/**
	 * 价格修改  审核页面List
	 * @param:flag:"apply",为审核申请草稿页面 ;"",为审核页面
	 * @return
	 */
	public String toPriceAuditListPage(){
		return "toPriceAuditListPage";
	}
	public String toPriceAuditApplyListPage(){
		return "toPriceAuditApplyListPage";
	}	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void productPriceAuditList(){
		request = this.getRequest();
		String userCode=getUserCodeFromSession();
		UserInfoBean userInfo=getUserInfo(userCode);
		String shopId=userInfo.getShopId();
		String corpId = userInfo.getCorpId();
		
		String productName  = request.getParameter("productName")==null?"":request.getParameter("productName");
		String status  = request.getParameter("status")==null?"":request.getParameter("status");
		String flag = request.getParameter("flag")==null?"":request.getParameter("flag");
		String frmStartTime = request.getParameter("frmStartTime")==null?"":request.getParameter("frmStartTime");
		String frmEndTime = request.getParameter("frmEndTime")==null?"":request.getParameter("frmEndTime");
		String result = "";
		try {
			dataGridJson = new EasyuiDataGridJson();
			HashMap map = new HashMap();
			map.put("corpId",corpId);	//公众号id
			map.put("shopId", shopId);	//商铺id
			map.put("productName", productName);
			map.put("status", status);
			map.put("flag", flag);
			map.put("frmStartTime", frmStartTime);
			map.put("frmEndTime", frmEndTime);
			map.put("startNo",Integer.valueOf(getStartIndexMysql()));
			map.put("pageRows",Integer.valueOf(getEndIndexMysql()));
			
			List<Map> productList = new ArrayList();
			productList = productPriceService.getProductAuditList("ProductPriceBean.getProductAuditList", map);
			long productCount = productPriceService.getProductAuditCount("ProductPriceBean.getProductAuditListLength", map);//查询总记录数
			
			dataGridJson.setRows(productList);
			dataGridJson.setTotal(productCount);
			result = JSONObject.fromObject(dataGridJson).toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			str2Resp(result);
		}
	}
	/**
	 * 商品价格审核  UI
	 */
	public String auditPrice(){
		request = getRequest();
		String status = request.getParameter("status")==null?"":request.getParameter("status");
		String productId = request.getParameter("productId")==null?"":request.getParameter("productId");
		String passed = request.getParameter("passed")==null?"":request.getParameter("passed");
		String uuid = request.getParameter("uuid")==null?"":request.getParameter("uuid");
		String appFlag = request.getParameter("appFlag")==null?"":request.getParameter("appFlag");
		Map<String, String> map = new HashMap<String, String>();
		map.put("productId", productId);
		map.put("status", "1");
		//商品信息
		Map<String, Object> proInfo = postTradeService.getProInfo(map);
		//产品价格
//		List<Map<String, Object>> priceList = productPriceService.getProductPrice("ProductPriceBean.getProductList", map);
//		if(priceList.size()>0&&priceList!=null){
//			request.setAttribute("flag", "true");
//			status = priceList.get(0).get("STATUS") + "";			
//		}
		String itemName = postTradeService.getCascadeName((String)proInfo.get("categoryCode"));
		request.setAttribute("productId", productId);//商品编码传入页面
		request.setAttribute("pro", proInfo);
		request.setAttribute("itemName", itemName);
		request.setAttribute("status", status);
		request.setAttribute("passed", passed);
		request.setAttribute("uuid", uuid);
		request.setAttribute("appFlag", appFlag);
		
		return "toAuditPricePage";
	}
	/**
	 * 商品价格审核 (批量或单一审核) 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void audit(){
		request = this.getRequest();
		String userCode=getUserCodeFromSession();
		//UserInfoBean userInfo=getUserInfo(userCode);
		//String shopId = userInfo.getShopId();
		//String corpId = userInfo.getCorpId();
		String productId = request.getParameter("productId")==null?"":request.getParameter("productId");
		String status = request.getParameter("status")==null?"":request.getParameter("status");
		String reason = request.getParameter("reason")==null?"":request.getParameter("reason");		
		String result = "1";
		try {
			String[] productIds = productId.split(",");
			for (int i = 0; i < productIds.length; i++) {
				HashMap map = new HashMap();
				map.put("productId", productIds[i]);
				map.put("auditPerson", userCode);
				map.put("reason", reason);
				map.put("status", status);
				int historyNum = productPriceService.getHistoryVersion("ProductPriceBean.getHistoryVersion", map);
				
				if(status.equals("2")){//申请通过
					//根据productId，将price的表的数据备份到history中
					List<Map> priceList = productPriceService.getPriceTableList("ProductPriceBean.getPriceTableList", map);
					for (int j = 0; j < priceList.size(); j++) {
						HashMap priceMap = new HashMap();
						priceMap.put("productId", priceList.get(j).get("PRODUCT_ID"));
						priceMap.put("shopId", priceList.get(j).get("SHOP_ID"));
						priceMap.put("corpId", priceList.get(j).get("CORP_ID"));
						priceMap.put("status", priceList.get(j).get("STATUS"));
						priceMap.put("uuid", UUID.randomUUID().toString());
						priceMap.put("sortNum", priceList.get(j).get("SORT_NUM"));				
						priceMap.put("purchasePrice", priceList.get(j).get("PRODUCT_PRICE"));				
						priceMap.put("purchaseLow", priceList.get(j).get("PURCHASE_LOW"));
						priceMap.put("purchaseType", priceList.get(j).get("PRODUCT_TYPE"));
						priceMap.put("purchaseUp", priceList.get(j).get("PURCHASE_UP"));
						priceMap.put("historyNum", historyNum);
						productPriceService.addPriceToHistory("ProductPriceBean.addPriceToHistory", priceMap);
					}
					
					//根据productId删除price表记录
					productPriceService.delPriceTable("ProductPriceBean.delPriceTable", map);
					
					//将price update表数据，写入price表
					map.put("status", 1);
					List<Map<String, Object>> updateList = productPriceService.getProductPrice("ProductPriceBean.getProductList", map);
					for (int k = 0; k < updateList.size(); k++) {
						HashMap updateMap = new HashMap();
						updateMap.put("productId", updateList.get(k).get("PRODUCT_ID"));
						updateMap.put("shopId", updateList.get(k).get("SHOP_ID"));
						updateMap.put("corpId", updateList.get(k).get("CORP_ID"));
						updateMap.put("status", 1);
						updateMap.put("uuid", updateList.get(k).get("UUID"));
						updateMap.put("sortNum", updateList.get(k).get("SORT_NUM"));				
						updateMap.put("purchasePrice", updateList.get(k).get("PRODUCT_PRICE"));				
						updateMap.put("purchaseLow", updateList.get(k).get("PURCHASE_LOW"));
						updateMap.put("purchaseType", updateList.get(k).get("PRODUCT_TYPE"));
						updateMap.put("purchaseUp", updateList.get(k).get("PURCHASE_UP"));
						
						productPriceService.addAuditToPrice("ProductPriceBean.addAuditToPrice",updateMap);
					}
					
					//更新price update表，修改状态 审核
					map.put("status", 2);
					productPriceService.modifyProductPrice("ProductPriceBean.modifyProductPrice",map);
				}else if(status.equals("3")){//未通过
					//更新price update表，修改状态 审核
					map.put("status", 3);
					productPriceService.modifyProductPrice("ProductPriceBean.modifyProductPrice",map);
				
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "2";
		} finally {
			str2Resp(result);
		}
	}
	
}
